#!/usr/bin/env python3
# coding=utf-8
import requests
import logging
import oss2

from flask import Flask, request, jsonify
from aip import AipOcr
from io import BytesIO
from psd_tools import PSDImage
from psd_tools.psd import PSD
from urllib.parse import unquote

app = Flask(__name__)

auth = oss2.Auth('', '')
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'feima-analysis-public-test')

weather_key = "57ec79d679004745aa65c283c3775ed4"

APP_ID = "oss-APP_ID"
API_KEY = "oss-API_KEY"
SECRET_KEY = "oss-SECRET_KEY"

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s "  # 配置输出日志格式
DATE_FORMAT = '%Y-%m-%d  %H:%M:%S '  # 配置输出时间的格式

logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=r"log/flask.log")


@app.route("/city/<province>/<city>")
def get_city(province, city):
    url = f"https://geoapi.heweather.net/v2/city/lookup?key={weather_key}&location={city}&adm={province}"
    r = requests.get(url)
    return r.text


@app.route("/weather/<location>")
def get_weather(location):
    url = f"https://devapi.heweather.net/v7/weather/now?key={weather_key}&location={location}"
    r = requests.get(url)
    return r.text


@app.route("/ocr", methods=["POST"])
def get_ocr_msg():
    fp = request.files.get("file")
    data = fp.read()
    msg = client.basicAccurate(data)
    if msg.get("error_code") is not None and msg.get("error_code") == 19:
        msg = client.basicGeneral(data)
    logging.info("orc msg: %s" % msg)
    wrods = msg.get("words_result")
    res = ""
    for word in wrods:
        res += word.get("words")
    dic = {"msg": res}
    return dic


@app.route("/psd", methods=["POST"])
def parse_psd():
    res = dict()
    data = request.get_json()
    url_list = data.get("url")
    tar_list = data.get("target")
    psd_dict = dict()
    for url in url_list:
        resp = requests.get(url)
        f = BytesIO(resp.content)
        psd = PSDImage(PSD.read(f))
        psd_dict[url] = psd
    for tar in tar_list:
        param_err = True
        width, height = tar.get("width"), tar.get("height")
        for key, value in psd_dict.items():
            if (width / height) != value.width / value.height:
                continue
            file_name = unquote(key[key.rindex("/") + 1:-4], "UTF-8")
            res_img = value.compose().resize((width, height))
            res_file = BytesIO()
            res_img.save(res_file, format="png")
            bucket.put_object("video/%s.png" % file_name, res_file.getvalue())
            tar["ossUrl"] = "https://feima-analysis-public-test.oss-cn-hangzhou.aliyuncs.com/video/%s.png" % file_name
            tar["fileLen"] = len(res_file.getvalue())
            param_err = False
            break
        if param_err:
            res["code"], res["msg"] = 500, "PSD尺寸不正确"
            return jsonify(res)
    res["code"], res["msg"], res["data"] = 200, "请求成功", tar_list
    return jsonify(res)


# 线上使用 gunicorn -b 0.0.0.0:8080 -w 4 run:app 命令启动
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
